package com.jzr.bedside.ui

import android.annotation.SuppressLint
import android.os.Build
import android.os.Environment
import android.view.View
import android.widget.Button
import android.widget.CompoundButton
import android.widget.EditText
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.utils.*
import com.jzr.bedside.R
import com.jzr.bedside.base.BaseActivity
import com.jzr.bedside.base.BaseApplication
import com.jzr.bedside.bean.*
import com.jzr.bedside.bean.body.RecordBody
import com.jzr.bedside.presenter.contract.SettingActivityContract
import com.jzr.bedside.presenter.impl.SettingActivityImpl
import com.jzr.bedside.ui.adapter.CheckDeptApadter
import com.jzr.bedside.utils.CommonUtil
import com.jzr.bedside.utils.DownloadFileListener
import com.jzr.bedside.utils.OkHttpUtil
import com.jzr.bedside.utils.PreferUtil
import com.jzr.bedside.view.CustomDialog
import kotlinx.android.synthetic.main.actionbar_root_layout.*
import kotlinx.android.synthetic.main.include_setting_system.*
import kotlinx.android.synthetic.main.include_setting_system_info.*
import java.io.File
import java.lang.Exception

class SettingActivity : BaseActivity(), View.OnClickListener, SettingActivityContract.View,
    CompoundButton.OnCheckedChangeListener, CheckDeptApadter.onListItemClick {

    private val mPresenter = SettingActivityImpl(this)
    private var apadter: CheckDeptApadter? = null
    private var dialogDeptList: CustomDialog? = null
    private var dialogBinDing: CustomDialog? = null
    private var edDeptCode:EditText?= null
    private var edBedCode:EditText?=null

    override fun getLayoutId(): Int {
        return R.layout.activity_setting
    }

    override fun attachView() {
        mPresenter.attachView(this)
    }

    override fun detachView() {
        mPresenter.detachView()
    }

    override fun initView() {

        edServiceIp.setText(PreferUtil.getInstance().serviceIp)
        edServicePort.setText(PreferUtil.getInstance().serverPort)
        edLookIp.setText(PreferUtil.getInstance().socketip)

        switchWifi.isChecked = NetworkUtils.isWifiConnected()
        switchWifi.setOnCheckedChangeListener(this)
        tvWifiInfo.text = CommonUtil.getWifiInfo(this)

        tvAppInfo.text = AppUtils.isSystemApp(this).toString()

        tvSnInfo.text = Build.SERIAL
        tvIpInfo.text = CommonUtil.getIP()
        tvVersionInfo.text = AppUtils.getAppVersionName(this)
        tvMacInfo.text = DeviceUtils.getMacAddress()
        edPass.setText(PreferUtil.getInstance().pass)

        ivRight.setOnClickListener(this)
        butConnecttest.setOnClickListener(this)
        btCheckBedNo.setOnClickListener(this)
        tvCheckBedNo.setOnClickListener(this)
        tvCheckDeptNo.setOnClickListener(this)
        btCheckDeptNo.setOnClickListener(this)
        btnPass.setOnClickListener(this)
        tvWifi.setOnClickListener(this)
        rlCheckUpater.setOnClickListener(this)
        mPresenter.getDeviceInfo("deviceNo", Build.SERIAL)

    }

    override fun onDestroy() {
        super.onDestroy()
        PreferUtil.getInstance().serviceIp = edServiceIp.text.toString()
        PreferUtil.getInstance().serverPort = edServicePort.text.toString()
        PreferUtil.getInstance().socketip = edLookIp.text.toString()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.ivRight -> {  // 退出
                finish()
            }
            R.id.butConnecttest -> { // 连接测试
                PreferUtil.getInstance().serviceIp = edServiceIp.text.toString()
                PreferUtil.getInstance().serverPort = edServicePort.text.toString()
                mPresenter.connectTest()
            }
            R.id.btCheckBedNo -> {   // 绑定床位
                val body = RecordBody()
                body.appVersion = AppUtils.getAppVersionCode(this)
                body.deptCode = PreferUtil.getInstance().deptCode
                body.deviceIp = CommonUtil.getIP()
                body.deviceMac = DeviceUtils.getMacAddress()
                body.deviceNo = Build.SERIAL
                body.deviceType = 0
                body.registerBed = PreferUtil.getInstance().bedCode
                mPresenter.getBindingBedNo(body)
            }
            R.id.tvCheckBedNo -> {   // 选择床位号
                mPresenter.getCheckDeptNo()
            }
            R.id.tvWifi -> {   // 打开WIFI设置页面
                NetworkUtils.openWirelessSettings()
            }
            R.id.rlCheckUpater -> {  // 检查更新
                mPresenter.getLastVersion(this,"softType","0")
            }
            R.id.btnPost -> {  // 手动绑定Dialog
                hideDeptListDialog()
                showBinDingDialog()
            }
            R.id.btnSd -> {  // 手动绑定
                if(StringUtils.isEmpty(edDeptCode?.text.toString())){
                    ToastUtils.showLongToast("请输入科室")
                    return
                }
                if(StringUtils.isEmpty(edBedCode?.text.toString())){
                    ToastUtils.showLongToast("请输入床位号")
                    return
                }
                PreferUtil.getInstance().deptCode = edDeptCode?.text.toString()
                PreferUtil.getInstance().bedCode = edBedCode?.text.toString()
                val body = RecordBody()
                body.appVersion = AppUtils.getAppVersionCode(this)
                body.deptCode = PreferUtil.getInstance().deptCode
                body.deviceIp = CommonUtil.getIP()
                body.deviceMac = DeviceUtils.getMacAddress()
                body.deviceNo = Build.SERIAL
                body.deviceType = 0
                body.registerBed = PreferUtil.getInstance().bedCode
                mPresenter.getBindingBedNo(body)
                hideBinDingDialog()
            }
            R.id.btnPass->{
                if(StringUtils.isEmpty(edPass.text.toString())){
                    ToastUtils.showShortToast(  "请输入密码")
                }else{
                    PreferUtil.getInstance().pass= edPass.text.toString()
                    ToastUtils.showShortToast("设置成功")
                }
            }
        }
    }

    override fun connectTestSuccess(data: ConnectTestBean?) {
        ToastUtils.showShortToast("连接成功")
        ivServicePort.setBackgroundResource(R.mipmap.test_result_sucess)
    }

    override fun getBindingBedNoSuccess(data: BindingBedBean?) {
        ToastUtils.showShortToast("绑定床位成功")
    }

    override fun getCheckBedNoSuccess(data: CheckBedListBean?) {

        val checkDataBeanList = mutableListOf<BaseCheckDataBean>()
        for (item in data!!.data) {
            val checkDataBean = BaseCheckDataBean()
            checkDataBean.code = item?.code
            checkDataBean.name = item?.name
            checkDataBeanList.add(checkDataBean)
        }
        apadter?.setNewData(checkDataBeanList)
        apadter?.setAdapterType(1)
        apadter?.notifyDataSetChanged()

    }

    override fun getCheckDeptNoSuccess(data: DeptCodeListBean?) {
        showDeptListDialog(data)
    }

    @SuppressLint("SetTextI18n")
    override fun getDeviceInfoSuccess(data: DeviceInfoBean?) {
        if (data?.data?.registerState == 1) {   //绑定的状态 0:未绑定 1:绑定中
            tvCheckBedNo.text = data.data?.deptName + "  " + data.data?.registerBed
        }
    }

    /**
     * 检查更新
     */
    override fun getLastVersionSuccess(data: LastVersionBean?) {
        val path =
            Environment.getExternalStorageDirectory().path + "/JzrApk/"
        if (AppUtils.getAppVersionCode(this) < data?.data?.version!!) {
            showLoadingDialog("正在下载.....")
            OkHttpUtil.download(data.data?.url, path, object : DownloadFileListener {
                override fun onDownloading(progress: Int) {
                    LogUtils.e("name", "progress == $progress")
                }

                override fun onDownloadFailed(e: Exception?) {
                    dismissLoadingDialog()
                    runOnUiThread {
                        ToastUtils.showShortToast("下载失败...")
                    }
                }

                override fun onDownloadSuccess(file: File?) {
                    dismissLoadingDialog()
                    runOnUiThread {
                        ToastUtils.showShortToast("下载成功...")
                    }
                   CommonUtil.installApk(this@SettingActivity,file!!)
                }
            })
        }else{
            ToastUtils.showShortToast("无新版本...")
        }

    }

    override fun showError(message: String?) {
        ToastUtils.showShortToast(message)
    }

    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        if (!isChecked) {
            tvWifiInfo.text = ""
        } else {
            tvWifiInfo.text = CommonUtil.getWifiInfo(this)
        }
        NetworkUtils.setWifiEnabled(isChecked)
    }

    private fun hideDeptListDialog() {
        if (dialogDeptList != null && dialogDeptList?.isShowing!!) {
            dialogDeptList?.dismiss()
            dialogDeptList = null
        }
    }
    private fun hideBinDingDialog() {
        if (dialogBinDing != null && dialogBinDing?.isShowing!!) {
            dialogBinDing?.dismiss()
            dialogBinDing = null
        }
    }

    private  fun showBinDingDialog(){
        hideBinDingDialog()
        val view =
            View.inflate(BaseApplication.getContext(), R.layout.dialog_binding, null)
        val btnSd = view.findViewById<Button>(R.id.btnSd)
         edDeptCode = view.findViewById<EditText>(R.id.edDeptCode)
         edBedCode = view.findViewById<EditText>(R.id.edBedCode)
        btnSd.setOnClickListener(this)

        dialogDeptList = CustomDialog(this,  view, R.style.MyDialog)
        dialogDeptList?.setCancelable(true)
        dialogDeptList?.show()
    }

    private fun showDeptListDialog(checkDeptBean: DeptCodeListBean?) {
        hideDeptListDialog()
        val view =
            View.inflate(BaseApplication.getContext(), R.layout.dialog_dept_list, null)
        val rvDeptList = view.findViewById<RecyclerView>(R.id.rv_dept_list)
        val btnPost = view.findViewById<Button>(R.id.btnPost)
        btnPost.setOnClickListener(this)

        val checkDataBeanList = mutableListOf<BaseCheckDataBean>()
        for (item in checkDeptBean!!.data) {
            val checkDataBean = BaseCheckDataBean()
            checkDataBean.code = item?.code
            checkDataBean.name = item?.name
            checkDataBeanList.add(checkDataBean)

        }

        apadter = CheckDeptApadter(checkDataBeanList)
        rvDeptList.layoutManager = LinearLayoutManager(this)
        rvDeptList.adapter = apadter
        dialogDeptList = CustomDialog(this, 500, 500, view, R.style.MyDialog)
        dialogDeptList?.setCancelable(true)
        dialogDeptList?.show()
        apadter?.setAdapterType(0)
        apadter?.onListItemClick(this)

    }

    @SuppressLint("SetTextI18n")
    override fun onListItemClick(item: BaseCheckDataBean?) {
        if (apadter?.type == 0) {
            PreferUtil.getInstance().deptCode = item?.code
            PreferUtil.getInstance().deptName = item?.name
            mPresenter.getCheckBedNo("deptCode", item?.code.toString())
        } else {
            hideDeptListDialog()
            PreferUtil.getInstance().bedCode = item?.code
            PreferUtil.getInstance().bedName = item?.name
            tvCheckBedNo.text =
                PreferUtil.getInstance().deptName + "  " + PreferUtil.getInstance().bedName
        }

    }

}
